using DG.Tweening;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[RequireComponent(typeof(ScrollRect))]
public class SnapScrollView : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IEventSystemHandler
{
	public class UnityEventInt : UnityEvent<int>
	{
	}

	public float sensitivity = 30f;

	private ScrollRect _scrollView;

	private float _startDragPosition;

	private float _endDragPosition;

	private int _currentIndex;

	private List<SnapScrollViewElement> _elementsList;

	public UnityEventInt OnElementHighlighted = new UnityEventInt();

	private void Awake()
	{
		_scrollView = GetComponent<ScrollRect>();
	}

	private void OnEnable()
	{
		_elementsList = new List<SnapScrollViewElement>(GetComponentsInChildren<SnapScrollViewElement>());
	}

	public void OnBeginDrag(PointerEventData eventData)
	{
		Vector2 anchoredPosition = _scrollView.content.anchoredPosition;
		_startDragPosition = anchoredPosition.x;
		_currentIndex = GetClosestElement(_startDragPosition);
	}

	public void OnEndDrag(PointerEventData eventData)
	{
		Vector2 anchoredPosition = _scrollView.content.anchoredPosition;
		_endDragPosition = anchoredPosition.x;
		int num = GetClosestElement(_endDragPosition);
		if (num == _currentIndex)
		{
			float num2 = _endDragPosition - _startDragPosition;
			if (num2 < 0f - sensitivity)
			{
				num++;
			}
			else if (num2 > sensitivity)
			{
				num--;
			}
		}
		_currentIndex = num;
		_currentIndex = Mathf.Clamp(_currentIndex, 0, _elementsList.Count - 1);
		_scrollView.content.DOKill();
		_scrollView.content.DOAnchorPosX(_elementsList[_currentIndex].XPosition, 0.2f);
		OnElementHighlighted.Invoke(_currentIndex);
	}

	private int GetClosestElement(float position)
	{
		int num = -1;
		float num2 = 0f;
		for (int i = 0; i < _elementsList.Count; i++)
		{
			if (num < 0 || Mathf.Abs((float)_elementsList[i].XPosition - position) < num2)
			{
				num = i;
				num2 = Mathf.Abs((float)_elementsList[i].XPosition - position);
			}
		}
		return num;
	}
}
